//
//  HJMapVC.m
//  project
//
//  Created by jc on 2019/4/10.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJMapVC.h"
#import "HJMapLactionListView.h"
#import "HJLocationOJC.h"

@interface HJMapVC ()<UITextFieldDelegate,MAMapViewDelegate,AMapSearchDelegate,AMapLocationManagerDelegate,MapSearchDataListDelegate,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIView *searchBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mapView_top;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textTF_top;
@property (weak, nonatomic) IBOutlet UIView *mapView;
@property (weak, nonatomic) IBOutlet UITextField *imputTF;
@property (weak, nonatomic) IBOutlet UILabel *location;
@property (weak, nonatomic) IBOutlet UIView *listView;
@property (nonatomic,strong) NSString * locationCity;// 定位城市

@property (nonatomic,strong) HJMapLactionListView * locationListView;
@property (strong, nonatomic) MAMapView *mymapView;
@property (nonatomic,strong) AMapLocationManager *locationManager;
@property (strong,nonatomic) AMapSearchAPI *ASearch;
@property (nonatomic,strong) MAPointAnnotation *pointAnnotation;
@property (nonatomic,strong) AMapGeoPoint *locationPoint;
//存放搜索到的关键字
@property(nonatomic,strong)NSMutableArray *arrKeyList;
@end

@implementation HJMapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"选择位置";
    [self configRightNaviBtn];
//    self.mapView_top.constant =;
    self.textTF_top.constant = 20;
    self.listView.hidden = YES;
    self.imputTF.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:self.imputTF];
    [HJLocationOJC manager];
    [self setUplocationManager];
    
}
-(void)configRightNaviBtn {
    UIButton * sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sendBtn setTitle:@"发送" forState:0];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:0];
    sendBtn.frame = CGRectMake(0, 0, 40, 40);
    [sendBtn addTarget:self action:@selector(sendLocationClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigaitonBar.rightCustomView = sendBtn;
    [self.searchBgView rounded:UIRectCornerAllCorners radius:20];
}

-(void)sendLocationClicked {
    self.locationBlock([HJLocationOJC manager].poiName, [HJLocationOJC manager].longitude, [HJLocationOJC manager].latitude, [HJLocationOJC manager].citycode, self.locationCity);
    [self.navigationController popViewControllerAnimated:YES];
}
-(NSMutableArray *)arrKeyList {
    if (!_arrKeyList) {
        _arrKeyList = [NSMutableArray array];
    }
    return _arrKeyList;
}
//大头针
-(MAPointAnnotation *)pointAnnotation {
    if (!_pointAnnotation) {
        _pointAnnotation = [[MAPointAnnotation alloc] init];
    }
    return _pointAnnotation;
}
-(MAMapView *)mymapView {
    if (!_mymapView) {
        _mymapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 0, self.mapView.width, self.mapView.height)];
        _mymapView.delegate = self;
        _mymapView.backgroundColor = [UIColor clearColor];
        _mymapView.mapType = MAMapTypeStandard;
        _mymapView.showsCompass = NO;
        [_mymapView setShowsScale:NO];
        _mymapView.zoomLevel = 13.2;
        [_mymapView setUserTrackingMode:MAUserTrackingModeNone animated:YES]; //地图不跟着位置移动
        
        UITapGestureRecognizer *lpress = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        lpress.delegate = self;
        [_mymapView addGestureRecognizer:lpress];//m_mapView
    }
    return _mymapView;
}
#pragma mark -- 初始化定位和搜索类
-(void)setUplocationManager {
    [self.mapView addSubview:self.mymapView];
    
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    self.locationManager.distanceFilter = kCLLocationAccuracyBest;
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    [self.locationManager setLocatingWithReGeocode:YES];
    [self.locationManager startUpdatingLocation];
    //初始化搜索类
    self.ASearch = [[AMapSearchAPI alloc] init];
    self.ASearch.delegate = self;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}
//长按手势
- (void)longPress:(UIGestureRecognizer*)gestureRecognizer {
//    if (gestureRecognizer.state != UIGestureRecognizerStateBegan) return;
    [self.view endEditing:YES];
    //坐标转换
    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
    CLLocationCoordinate2D touchMapCoordinate =
    [self.mymapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
    [self.mymapView removeAnnotation:self.pointAnnotation];
    
    //逆地理编码
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:touchMapCoordinate.latitude longitude:touchMapCoordinate.longitude];
    regeo.requireExtension = YES;
    
    [self.ASearch AMapReGoecodeSearch:regeo];
    self.pointAnnotation.coordinate = touchMapCoordinate;
    //添加大头针到地图
    [self.mymapView addAnnotation:self.pointAnnotation];
    //是否显示在屏幕中心
    [self.mymapView setCenterCoordinate:touchMapCoordinate animated:YES];
}

#pragma AMapLocationManagerDelegate 定位成功
-(void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
    
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    regeo.requireExtension = YES;
    [HJLocationOJC manager].latitude = location.coordinate.latitude;
    [HJLocationOJC manager].longitude = location.coordinate.longitude;
    
    [self.ASearch AMapReGoecodeSearch:regeo];
    self.pointAnnotation.coordinate = location.coordinate;
    [self.mymapView addAnnotation:self.pointAnnotation];
    [self.mymapView setCenterCoordinate:location.coordinate animated:YES];
    
    //停止定位
    [self.locationManager stopUpdatingLocation];
}
-(void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    [self showErrorHUDWithError:@"定位失败，请重新定位"];
}
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager*)locationManager {
    [locationManager requestWhenInUseAuthorization];
}
#pragma mark --MAMapViewDelegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAAnnotationView*annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (!annotationView) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= NO;
        annotationView.image = [UIImage imageNamed:@"home_store_address30"];
        annotationView.draggable = YES;
        annotationView.centerOffset = CGPointMake(0, -18);
        annotationView.annotation = annotation;
        
        return annotationView;
    }
    return nil;
}
#pragma mark --逆地理编码成功回调
-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {
    if (response.regeocode !=nil) {
        self.pointAnnotation.title = response.regeocode.formattedAddress;
        self.pointAnnotation.subtitle = nil;
        self.location.text = response.regeocode.formattedAddress;
        if ([response.regeocode.addressComponent.city isEqualToString:@""]||response.regeocode.addressComponent.city==nil) {
            self.locationCity = response.regeocode.addressComponent.district;
        } else {
            self.locationCity = response.regeocode.addressComponent.city;
        }
        [HJLocationOJC manager].province = response.regeocode.addressComponent.province;
        [HJLocationOJC manager].city = self.locationCity;
        [HJLocationOJC manager].citycode = response.regeocode.addressComponent.citycode;
        [HJLocationOJC manager].adcode = response.regeocode.addressComponent.adcode ;
        [HJLocationOJC manager].township = response.regeocode.addressComponent.township;
        [HJLocationOJC manager].neighborhood = response.regeocode.addressComponent.neighborhood;
        [HJLocationOJC manager].building = response.regeocode.addressComponent.building;
        [HJLocationOJC manager].streetName = response.regeocode.formattedAddress;
        if (response.regeocode.pois.count>0) {
            AMapPOI * poi = response.regeocode.pois[0];
            [HJLocationOJC manager].poiName = poi.name;
        }
        [self.mymapView addAnnotation:self.pointAnnotation];
        self.locationPoint = request.location;
    }else {
        self.pointAnnotation.title = @"未知地址";
    }
}
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error {
    NSLog(@"Error: %@", error);
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([textField isFirstResponder]) {
        self.listView.hidden = YES;
        [textField resignFirstResponder];
        [self Search];
    }
    return YES;
}

-(void)textFieldChanged:(id)textTF {
    [self Search];
}

#pragma  mark --搜索
-(void)Search {
    if (!self.imputTF.text.length) return;
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.city = self.locationCity;
    request.keywords = self.imputTF.text;
    request.sortrule = 0;
    request.requireExtension = YES;
    request.cityLimit = NO;
    request.page = 1;
    request.offset = 50;
    request.types = @"050000|060000|070000|080000|090000|100000|110000|120000|130000|140000|150000|160000|170000|180000|190000|200000|220000|970000|990000";
    //发送
    [self.ASearch AMapPOIKeywordsSearch:request];
}
-(void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    if (response.pois.count!=0) {
        self.arrKeyList = [NSMutableArray arrayWithArray:response.pois];
        NSMutableArray *keyListArr = [NSMutableArray array];
        for (AMapPOI *poiResult in self.arrKeyList) {
            [keyListArr addObject:poiResult.name];
        }
        self.listView.hidden = NO;
        self.locationListView.hidden = NO;
        self.locationListView.dataSoures = keyListArr;
    }
}

// 定位按钮
- (IBAction)starLocationBtnClicked:(id)sender {
    [self.locationManager startUpdatingLocation];
}

#pragma mark -- locationListView创建
-(HJMapLactionListView *)locationListView {
    if (!_locationListView) {
        _locationListView = [[HJMapLactionListView alloc]initWithFrame:CGRectMake(0, 0, self.listView.width, self.listView.height)];
        _locationListView.hidden = YES;
        _locationListView.delegate = self;
        [self.listView addSubview:_locationListView];
    }
    return _locationListView;
}

- (void)loactionListView:(HJMapLactionListView *)locationListView didSelectListItemAtIndex:(NSInteger)selectedIndex {
    self.listView.hidden = YES;
    self.locationListView.hidden = YES;
    [self.imputTF resignFirstResponder];
    
    AMapPOI *poiResult = self.arrKeyList[selectedIndex];
    CLLocationCoordinate2D coor;
    coor.latitude = poiResult.location.latitude;
    coor.longitude = poiResult.location.longitude;
    if (coor.latitude == 0.0&&coor.longitude == 0.0) {
        [self showErrorHUDWithError:@"没有找到该位置"];return;
    }
    
    self.imputTF.text = poiResult.name;
    self.pointAnnotation.coordinate = coor;
    self.pointAnnotation.title = poiResult.name;
    self.pointAnnotation.subtitle = poiResult.address;
    
    self.locationPoint = poiResult.location;
    self.location.text = poiResult.address;
    //逆地理编码
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:coor.latitude longitude:coor.longitude];
    regeo.requireExtension = YES;
    [self.ASearch AMapReGoecodeSearch:regeo];
    self.pointAnnotation.coordinate = coor;
    
    //加载搜索位置大头针到地图
    [self.mymapView addAnnotation:self.pointAnnotation];
    //地图中心点设置为搜索的点
    [self.mymapView setCenterCoordinate:coor animated:YES];
}
@end
